import com.mysql.jdbc.JDBC4PreparedStatement;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 东莞呵呵
 * Date:2022-08-26
 * Time:14:46
 */
public class JDBC {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");

        //2、让代码与数据库建立联系
        Connection connection = dataSource.getConnection();

        //控制台输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号->");
        int id = scanner.nextInt();
        //scanner.next();
        System.out.println("请输入姓名->");
        String name = scanner.next();

        //3、构造sql语句
        String str = "insert into student values(?, ?)";
        PreparedStatement statement = connection.prepareStatement(str);
        statement.setInt(1, id);
        statement.setString(2, name);
        System.out.println("statement:" + statement);
        //4、执行sql语句
        int n = statement.executeUpdate();
        System.out.println("n=" + n);

        //5、释放资源
        statement.close();
        connection.close();

    }
}
